package com.bwie.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.utils.R;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.Dict;
import com.bwie.mapper.DictMapper;
import com.bwie.service.DictService;

import javax.annotation.PostConstruct;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService{

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String key = "dict:";


    /**
     * @description:项目自启动
     * @author: Zero
     * @date: 2025/10/24 19:36
     * @param: [parentId]
     * @return: com.bwie.utils.R
     **/
    @PostConstruct
    public void dict(){
        System.out.println("项目字典，初始化并加载致 redis 中");
        //查询所有的 dict 的数据
         List<Dict> dictList = dictMapper.selectList(null);
        //将数据 循环遍历存入 redis 中
        if (ObjectUtils.isNotEmpty(dictList)){
            for (Dict dict : dictList) {
                redisTemplate.opsForHash().put(key+dict.getParentId().toString(),dict.getDictId().toString(), JSONObject.toJSONString(dict));
            }
        }
        System.out.println("项目初始化结束");
    }



    @Override
    public R selectDictByPid(Integer parentId) {
        // 先判断缓存里面是否存在数据
        Boolean hasKey = redisTemplate.hasKey(key + parentId);
        // 如果缓存中存在数据就取出，返回前端
        if (hasKey && hasKey != null){
            List<Object> values = redisTemplate.opsForHash().values(key + parentId);
            ArrayList<Dict> list = new ArrayList<>();
            for (Object o : values) {
                list.add(JSONObject.parseObject(o.toString(), Dict.class));
            }
            return R.OK(list);
        }
        // 如果不存在就查询数据库，病重新加载致缓存中
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId,parentId);
        List<Dict> dictList = dictMapper.selectList(wrapper);
        if (ObjectUtils.isNotEmpty(dictList)){
            for (Dict dict : dictList) {
                redisTemplate.opsForHash().put(dict.getParentId().toString(),dict.getDictId().toString(),JSONObject.toJSONString(dictList));
            }
        }
        return R.OK(dictList);
    }
}
